package org.jeecg.modules.phone.mapper;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.jeecg.modules.phone.entity.PhoneAccountTaskJoinTaskVo;
import org.jeecg.modules.phone.entity.PhoneEntityTask;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.jeecg.modules.phone.entity.PhoneEntityTaskVo;

/**
 * @Description: 实体任务调度
 * @Author: jeecg-boot
 * @Date:   2022-08-31
 * @Version: V1.0
 */
public interface PhoneEntityTaskMapper extends BaseMapper<PhoneEntityTask> {

    @Select("SELECT a.*, c.task_name " +
            "FROM phone_entity_task a " +
            "LEFT JOIN phone_task_children c ON a.task_children_id = c.id " +
            "${ew.customSqlSegment}")
    IPage<PhoneEntityTaskVo> pageList(Page<PhoneEntityTaskVo> page,  @Param(Constants.WRAPPER) Wrapper<PhoneEntityTask> queryWrapper);

    /*执行中的手机，待执行最小id, 排除有执行中任务的*/
    @Select("SELECT  t.*\n" +
            "FROM  phone_entity_task t\n" +
            "LEFT JOIN (  SELECT   id  FROM   phone_entity  WHERE   entity_status = '执行中'\n" +
            ") y ON t.entity_id = y.id\n" +
            "LEFT JOIN (  SELECT   MIN(id) id  FROM   phone_entity_task  WHERE   task_status = '待执行'  GROUP BY   entity_id\n" +
            ") m ON m.id = t.id\n" +
            "LEFT JOIN (  SELECT DISTINCT   entity_id  FROM   phone_entity_task  WHERE   task_status = '执行中'\n" +
            ") r ON r.entity_id = t.entity_id\n" +
            "WHERE  t.task_status = '待执行'\n" +
            "AND y.id IS NOT NULL\n" +
            "AND m.id IS NOT NULL\n" +
            "AND r.entity_id IS NULL ")
    List<PhoneEntityTask> checkWaitRunTask( );
}
